<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="md-trophy"></Icon>
      服务管理
    </p>
    <a href="#" v-if="permission.service_create === '1'" slot="extra" @click.prevent="createServiceView">
      <Icon type="md-add-circle"></Icon>
      创建
    </a>
    <Modal v-model="createModal" draggable scrollable title="新建服务" :footer-hide=true>
      <Form ref="formCreate" :model="formCreate" :rules="ruleCreate" :label-width="80">
        <FormItem label="应用环境" prop="namespace_name">
          <Select v-model="formCreate.namespace_name" placeholder="Select your env">
            <Option v-for="item in namespaced" :key="item.label" :value="item.value">{{item.value}}</Option>
          </Select>
        </FormItem>
        <FormItem label="服务名称" prop="service_name">
          <Input v-model="formCreate.service_name" placeholder="Enter your service name"></Input>
        </FormItem>
        <FormItem label="服务端口" prop="service_port">
          <Input v-model="formCreate.service_port" placeholder="Enter your service port"></Input>
        </FormItem>
        <FormItem>
          <Button type="success" @click="createService('formCreate')">点击提交</Button>
          <Button type="warning" @click="createFormReset('formCreate')" style="margin-left: 8px">清空</Button>
          <Button type="info" @click="closeView('formCreate')" style="margin-left: 8px">关闭</Button>
        </FormItem>
      </Form>
    </Modal>
    <div style="padding-bottom: 10px;">
      <!-- <Row :gutter="16">
        <Col span="6">
          <Select v-model="namespace"  placeholder="请选择应用环境" @on-change="serviceData">
            <Option v-for="item in namespaced" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="6" offset="12">
          <Input search placeholder="Search ..." v-model="search_value" @on-search=searchService />
        </Col>
      </Row> -->
      <Row :gutter="24">
        <Col span="4">
          <Select v-model="cloud_name"  placeholder="请选择云平台" @on-change="GetCloudNamespaces">
            <Option v-for="item in cloud_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Select v-model="namespace"  placeholder="请选择命名空间" clearable @on-change="serviceData" ref="service_list">
            <Option v-for="item in namespaced" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4" offset="12">
          <Input search placeholder="Search ..." v-model="search_value" @on-search=searchService />
        </Col>
      </Row>
    </div>
    <Table border :loading="loading" :columns="columns" :data="data">
      <template slot-scope="{ row, index }" slot="action">
        <Button v-if="permission.service_delete === '1'" type="error" size="small" @click="remove(index)" style="margin-left:10px">删除</Button>
        <span v-else style="color:#ed4014">无权限</span>
      </template>
    </Table>
    <div style="padding-top: 10px;" v-if="count">
      <template>
        <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer @on-change="switchPage" @on-page-size-change="switchPageSize" />
      </template>
    </div>
  </Card>
</template>

<script>
import { namespaceList, serviceList, serviceCreate, serviceDelete } from '@/api/production'

  export default {
    data () {
      return {
        loading: false,
        count: '',
        page: 1,
        pageSize: 10,
        search_value: '',
        namespace: '',
        namespaced: [],
        createModal: false,
        formCreate: {
          namespace_name: '',
          service_name: '',
          service_port: '',
        },
        ruleCreate: {
          namespace_name: [
            { required: true, message: 'Please select the env', trigger: 'change' }
          ],
          service_name: [
            { required: true, message: 'The service name cannot be empty', trigger: 'blur' }
          ],
          service_port: [
            { required: true, message: 'The service port cannot be empty', trigger: 'blur' }
          ]
        },
        cloud_name: '',
        cloud_list: [
          {value: 'aliyun', label: '阿里云集群'},
          // {value: 'aws-stg', label: 'AWS-STG'},
          // {value: 'aws-prod', label: 'AWS-PROD'}
        ],
        columns: [
          {
            title: '服务名称',
            key: 'name'
          },
          {
            title: 'Service类型',
            key: 'type'
          },
          {
            title: 'ClusterIP',
            key: 'cluster_ip'
          },
          {
            title: '内部端点',
            key: 'internal_endpoint',
          },
          {
            title: '外部端点',
            key: 'external_endpoint',
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'center'
          }
        ],
        data: [],
        permission: ''
      }
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      GetCloudNamespaces () {
        this.$refs.service_list.clearSingleSelect();
        this.namespaced = [];
        this.data = [];
        this.count = 0;
        this.namespace_list({'cloud_name': this.cloud_name})
      },
      // 获取service列表数据
      namespace_list (cloud) {
        namespaceList(cloud).then(res => {
          var namespace_res = res.data.results
          for (const namespace in namespace_res) {
            if (namespace_res[namespace]['name']==='prod' || namespace_res[namespace]['name']==='uat') {
              var auth = this.permission[`production_${namespace_res[namespace]['name']}_view`]
              if (auth==='1') {
                var select_men = {
                  'value': namespace_res[namespace]['name'],
                  'label': namespace_res[namespace]['name']
                }
                this.namespaced.push(select_men)
              }
            } else {
              var select_men = {
                'value': namespace_res[namespace]['name'],
                'label': namespace_res[namespace]['name']
              }
              this.namespaced.push(select_men)
            }
          }
        })
      },
      //获取service数据
      serviceData () {
        this.loading = true;
        var params = {
          'cloud_name': this.cloud_name,
          'namespace_name':this.namespace,
          'Page': this.page,
          'PageSize': this.pageSize,
          'searchName': this.search_value
        }
        if (this.cloud_name.length != 0 && this.namespace !== undefined) {
          serviceList(params).then(res => {
            this.loading = false;
            this.count = res.data.count;
            this.data = res.data.results;
          }).catch(err => {
            this.$Message.error("列表获取失败!")
          })
        }
      },
      createServiceView () {
        if (this.namespace.length !=0) {
          this.createModal = true
        } else {
          this.$Message.error("请选择命名空间!")
        }
      },
      createService (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            serviceCreate(this.formCreate).then(res => {
              if (res.data.code === 500) {
                this.$Message.error({content:res.data.msg,duration: 0,closable: true})
              } else {
                this.$Message.success({content:res.data.msg,duration: 5,closable: true})
                this.serviceData()
              }
            }).catch(err => {
              this.$Message.error("接口请求失败!")
          })
          }
        })
      },
      createFormReset (name) {
        this.$refs[name].resetFields();
      },
      closeView (name) {
        this.createModal=false;
        this.createFormReset(name);
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        this.serviceData()
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.pageSize = pageSize
        this.serviceData()
      },
      // 搜索
      searchService () {
        this.loading = true;
        var params = {
          'cloud_name': this.cloud_name,
          'namespace_name': this.namespace,
          'searchName': this.search_value
        }
        if (this.namespace.length !=0 ) {
          serviceList(params).then(res => {
            this.loading = false;
            this.count = res.data.count
            this.data = res.data.results
          }).catch(err => {
            this.$Message.error('接口请求失败!')
          })
        } else {
          this.$Message.error("请选择应用环境!")
        }
      },
      // 删除
      remove (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>删除${this.data[index].name}后会导致关联应用无法正常访问，是否继续？</p>`,
          onOk: () => {
            var params = {
              'cloud_name': this.cloud_name,
              'namespace_name': this.namespace,
              'service_name': this.data[index].name
            }
            serviceDelete(params).then(res => {
              if (res.data.code !== 500) {
                this.$Message.success({content:res.data.msg,duration: 5,closable: true})
                this.serviceData()
                // 设置3s后再刷新一次数据
                setTimeout(() => {
                  this.serviceData()
                },3000)
              } else {
                this.$Message.error({content:res.data.msg,duration: 0,closable: true})
              }
            }).catch(err => {
              this.$Message.error({content:'删除失败!',duration: 0,closable: true})
            })
          },
          onCancel: () => {
            this.$Message.info('已取消删除');
          }
        })
      },
    },
    created () {
      this.get_permission();
      // this.namespace_list();
    }
  }
</script>